package com.obixlabs.commons.process;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HeartbeatThread extends Thread{
		
	private static final int DEFAULT_HEARTBEAT_MINS = 3;
	
	private static final Logger logger = LoggerFactory.getLogger(HeartbeatThread.class);
	
	private int heartbeatMinutes;
	private String processName;
	
	public HeartbeatThread(String processName)  { 
		setHeartbeatMinutes(DEFAULT_HEARTBEAT_MINS);
		setDaemon(false);
		setProcessName(processName);
	}
	
	@Override
	public void run() {
		while (true) {
			logger.info(ProcessUtil.getHeartbeatMessage(getProcessName()));
			try {
				Thread.sleep(TimeUnit.MINUTES.toMillis(this.heartbeatMinutes));
			} catch (InterruptedException exce) {
				logger.error("Thread interrupted. Possible application shutdown. Bailing Out!");
				break;
			}
		}
	}
	
	public int getHeartbeatMinutes() { return this.heartbeatMinutes; }
	public void setHeartbeatMinutes(int heartbeatMinutes) {
		if (heartbeatMinutes>0)
			this.heartbeatMinutes = heartbeatMinutes;
		else logger.warn("Ignoring invalid heartbeat interval {}.", heartbeatMinutes);
	}	
	
	public String getProcessName() { return this.processName; }
	public void setProcessName(String processName) 
	{ this.processName = processName; }
}
